/*
 * DatabaseUtil.java
 *
 * Created on __DATE__, __TIME__
 */

package com.ndood.code.ui;

import java.io.File;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import com.ndood.code.database.DbUtil;
import com.ndood.code.entity.filter.TableFilter;
import com.ndood.code.xml.ConfigXml;
import com.ndood.code.xml.DatabaseXml;
import com.ndood.code.xml.DataFilterMapXml;

/**
 * 贝帛吱付代码生成器 V2.4
 *
 * @author ndood
 *
 */
public class DatabaseUtil extends javax.swing.JFrame {

	private static final long serialVersionUID = -2322860513398536218L;

	/** Creates new form DatabaseUtil */
	public DatabaseUtil() {
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	@SuppressWarnings({"deprecation" })
	private void initComponents() {

		labelDbType = new JLabel();
		selectdbType = new javax.swing.JComboBox<String>();
		labelUsername = new JLabel();
		textUsername = new javax.swing.JTextField();
		labelPassword = new JLabel();
		textPassword = new javax.swing.JTextField();
		labelDb = new JLabel();
		selectDb = new javax.swing.JComboBox<String>();
		btnLink = new javax.swing.JButton();
		btnNext = new javax.swing.JButton();
		textAddress = new javax.swing.JTextField();
		textPort = new javax.swing.JTextField();
		labelAddress = new JLabel();
		labelPort = new JLabel();

		// setTitle("\u4f20\u667a\u5218\u5907\u4ee3\u7801\u751f\u6210\u56682.3");
		setTitle("贝帛吱付代码生成器2.4");
		setBackground(new java.awt.Color(204, 255, 204));
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosed(java.awt.event.WindowEvent evt) {
				formWindowClosed(evt);
			}

			public void windowOpened(java.awt.event.WindowEvent evt) {
				formWindowOpened(evt);
			}

			public void windowClosing(java.awt.event.WindowEvent evt) {
				formWindowClosing(evt);
			}
		});

		labelDbType.setText("选择数据库类型");

		selectdbType.setModel(new javax.swing.DefaultComboBoxModel<String>(new String[] { "--请选择--" }));

		labelUsername.setText("用户名");

		labelPassword.setText("密码");

		labelDb.setText("数据库");

		selectDb.setModel(new javax.swing.DefaultComboBoxModel<String>(new String[] { "--请选择数据库--" }));

		btnLink.setText("测试连接");
		btnLink.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnLinkActionPerformed(evt);
			}
		});

		btnNext.setLabel("跳过");
		btnNext.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnNextActionPerformed(evt);
			}
		});

		textUsername.setText("root");

		textPassword.setText("pay-boy");

		textAddress.setText("127.0.0.1");

		textPort.setText("3306");

		labelAddress.setText("服务器IP");

		labelPort.setText("端口");

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGap(75, 75, 75)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addComponent(labelPassword).addComponent(labelAddress).addComponent(labelPort).addComponent(labelDbType)
								.addComponent(labelUsername).addComponent(labelDb).addComponent(btnLink))
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addGroup(layout.createSequentialGroup()
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												btnNext, javax.swing.GroupLayout.PREFERRED_SIZE, 99,
												javax.swing.GroupLayout.PREFERRED_SIZE))
								.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
										.addGap(34, 34, 34)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(selectDb, javax.swing.GroupLayout.Alignment.TRAILING, 0,
														174, Short.MAX_VALUE)
												.addComponent(textUsername, javax.swing.GroupLayout.Alignment.TRAILING,
														javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
												.addComponent(selectdbType, javax.swing.GroupLayout.Alignment.TRAILING, 0,
														174, Short.MAX_VALUE)
												.addComponent(textAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 174,
														Short.MAX_VALUE)
												.addComponent(textPort, javax.swing.GroupLayout.DEFAULT_SIZE, 174,
														Short.MAX_VALUE)
												.addComponent(textPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 174,
														Short.MAX_VALUE))))
						.addGap(106, 106, 106)));
		layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup().addGap(53, 53, 53)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(labelDbType).addComponent(selectdbType, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGap(18, 18, 18)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(textAddress, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(labelAddress))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(textPort, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(labelPort))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(textUsername, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(labelUsername))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(labelPassword))
						.addGap(11, 11, 11)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addComponent(labelDb).addComponent(selectDb, javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
						.addGap(11, 11, 11)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(btnLink).addComponent(btnNext))
						.addContainerGap()));

		pack();
	}// </editor-fold>
		// GEN-END:initComponents

	private void formWindowClosing(java.awt.event.WindowEvent evt) {
		dispose();
		System.exit(0);
		System.out.println("释放");
	}

	private void formWindowClosed(java.awt.event.WindowEvent evt) {
		dispose();
		System.exit(0);
		System.out.println("释放");
	}

	private void formWindowOpened(java.awt.event.WindowEvent evt) {
		setLocationRelativeTo(null);

		dbMap = ConfigXml.readConfig();

		for (String key : dbMap.keySet()) {
			this.selectdbType.addItem(key);
		}

	}

	Map<String, Map<String, String>> dbMap;
	DbUtil util;
	Map<String, String> propertyMap;
	String db = "";

	/**
	 * 点击下一步事件监听
	 */
	private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {

		if (this.btnNext.getText().equals("下一步")) {
			this.btnNext.setText("运行中...");
			this.btnNext.setEnabled(false);

			// Step1: 选择数据库
			try {
				db = this.selectDb.getSelectedItem().toString();
			} catch (Exception e1) {
			}

			// Step2: 连接数据库
			util = new DbUtil();
			util.setDbName(db);// 设置数据库名称
			util.setDbType(this.selectdbType.getSelectedItem().toString());

			propertyMap = dbMap.get(util.getDbType());
			String url = propertyMap.get("url").replace("[ip]", this.textAddress.getText())
					.replace("[port]", this.textPort.getText()).replace("[db]", db);

			util.setDriverName(propertyMap.get("driverName"));
			util.setUrl(url);
			util.setDbName(db);
			util.setIp(this.textAddress.getText());
			util.setUserName(this.textUsername.getText());
			util.setPassWord(this.textPassword.getText());

			if (url.indexOf("&amp;") < 0 && url.indexOf("&") > 0) {
				url = url.replace("&", "&amp;");
			}
			propertyMap.put("url", url);

			// Step3: 生成db.xml文件
			final Thread t = new Thread(new Runnable() {
				public void run() {
					try {
						// 1 获取当前文件夹下的模板目录下的所有文件夹
						String basePath = new File("").getAbsolutePath() + "\\src\\main\\resources\\db";

						// 2 获取需要生成的table
						Map<String, TableFilter> tableMap = DataFilterMapXml.readTableMap(basePath);
						
						DatabaseXml.writeDatabaseXml(util, propertyMap, basePath, tableMap);
					} catch (Exception e) {
						e.printStackTrace();
						JOptionPane.showMessageDialog(null, "发生错误", "错误详情请查看error.log",
								JOptionPane.INFORMATION_MESSAGE);
					}

					CodeUtil codeUtil = new CodeUtil();
					codeUtil.setVisible(true);
					codeUtil.setDbInfo(db, textUsername.getText(), textPassword.getText());
					setVisible(false);

				}
			});
			t.start();

		} else {
			CodeUtil codeUtil = new CodeUtil();
			codeUtil.setVisible(true);
			codeUtil.setDbInfo(db, textUsername.getText(), textPassword.getText());

			setVisible(false);
		}
	}

	/**
	 * 连接数据库按钮点击事件
	 */
	private void btnLinkActionPerformed(java.awt.event.ActionEvent evt) {
		//
		btnLink.setText("连接中...");
		btnLink.setEnabled(false);

		final Thread t = new Thread(new Runnable() {
			public void run() {
				try {

					// Step1: 设置数据库访问Bean
					DbUtil util = new DbUtil();
					Map<String, String> map = dbMap.get(selectdbType.getSelectedItem());
					
					util.setDriverName(map.get("driverName"));
					String url = map.get("url").replace("[ip]", textAddress.getText())
							.replace("[port]", textPort.getText()).replace("[db]", "");

					util.setUrl(url);
					util.setUserName(textUsername.getText());
					util.setPassWord(textPassword.getText());

					// Step2: 获取数据库列表
					List<String> catalogs = util.getSchemas();
					selectDb.removeAllItems();
					for (String c : catalogs) {
						selectDb.addItem(c); 
					}

					JOptionPane.showMessageDialog(null, "连接成功", "提示", JOptionPane.DEFAULT_OPTION);
					btnNext.setText("下一步");

				} catch (ClassNotFoundException e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "无法加载驱动类", "提示", JOptionPane.OK_OPTION);

				} catch (SQLException e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "无法连接数据库，请核对连接信息是否正确", "提示", JOptionPane.OK_OPTION);

				} catch (Exception e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, "发生错误", "错误详情请查看error.log", JOptionPane.INFORMATION_MESSAGE);

				}

				btnLink.setEnabled(true);
				btnLink.setText("测试连接");

			}
		});
		t.start();

	}

	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new DatabaseUtil().setVisible(true);
			}
		});
	}

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JButton btnLink;
	private javax.swing.JButton btnNext;
	private javax.swing.JComboBox<String> selectdbType;
	private javax.swing.JComboBox<String> selectDb;
	private JLabel labelDbType;
	private JLabel labelUsername;
	private JLabel labelPassword;
	private JLabel labelDb;
	private JLabel labelAddress;
	private JLabel labelPort;
	private javax.swing.JTextField textUsername;
	private javax.swing.JTextField textPassword;
	private javax.swing.JTextField textAddress;
	private javax.swing.JTextField textPort;
	// End of variables declaration//GEN-END:variables

}